package br.com.vti.leilao.controller;

import br.com.vti.leilao.model.business.Business;
import br.com.vti.leilao.model.business.LanceBusiness;
import br.com.vti.leilao.model.business.exception.ApplicationException;
import br.com.vti.leilao.model.dao.Dao;
import br.com.vti.leilao.model.entity.Ganhador;
import br.com.vti.leilao.model.entity.Lance;
import br.com.vti.leilao.model.entity.Leilao;
import java.sql.SQLException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

/**
 *
 * @author ednardomatos
 */
public class LanceJob implements Job {
    
    public transient static final Logger logger = Logger.getLogger(LanceJob.class);

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        JobDataMap dataMap = jec.getJobDetail().getJobDataMap();
        Integer idLeilao = dataMap.getInt("idLeilao");
        Leilao leilao = getLeilao(idLeilao);
        if (leilao != null) {
            Lance lance = consultarUltimoLance(leilao);
            if (lance != null) {
                Integer tempo = qtdTempoRestante(new Date(), lance.getHoraLance(), leilao.getTempoDuracao());
                if (tempo <= 0) {
                    Ganhador ganhador = new Ganhador(null, lance);
                    salvarGanhador(ganhador);
                }
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    private Leilao getLeilao(Integer idLeilao) {
        Leilao leilaoAux = null;
        try {
            leilaoAux = new Leilao();
            leilaoAux.setId(idLeilao);
            WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
            Dao<Leilao> leilaoDao = (Dao<Leilao>) ctx.getBean("dao");
            leilaoAux = leilaoDao.procurarPorId(leilaoAux);
        } catch (SQLException ex) {
            logger.error(ex);
        }
        return leilaoAux;
    }
    
    @SuppressWarnings("unchecked")
    private Lance consultarUltimoLance(Leilao leilao) {
        Lance lance = new Lance();
        lance.setLeilaoFk(leilao);
        WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
        LanceBusiness lanceBusiness = (LanceBusiness) ctx.getBean("lanceBusiness");
        return lanceBusiness.consultarUltimoLance(lance);
    }
    
    @SuppressWarnings("unchecked")
    private void salvarGanhador(Ganhador ganhador) {
        if (ganhador != null) {
            WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
            Business<Ganhador, ApplicationException> ganhadorBusiness = (Business<Ganhador, ApplicationException>) ctx.getBean("ganhadorBusiness");
            try {
                List<Ganhador> lista = ganhadorBusiness.listarPorExemplo(ganhador, 1);
            } catch (ApplicationException e) {
                try {
                    ganhador.setQtdProduto(1);
                    ganhadorBusiness.inserir(ganhador);
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }
        }
    }
    
    private Integer qtdTempoRestante(Date dataAtual, Date dataUltimoLance, Integer tempoDuracao) {
        Integer res = 0;
        GregorianCalendar gc1 = new GregorianCalendar();
        gc1.setTime(dataAtual);
        
        GregorianCalendar gc2 = new GregorianCalendar();
        gc2.setTime(dataUltimoLance);
        
        Integer diff = Integer.parseInt(String.valueOf((gc1.getTimeInMillis() - gc2.getTimeInMillis())/1000));
        if (diff < tempoDuracao) {
            res = tempoDuracao - diff;  
        }
        return res;
    }
    
}
